package com.liao.cloudstorage.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.liao.cloudstorage.conf.MinioClientBean;
import com.liao.cloudstorage.entity.Bucket;
import com.liao.cloudstorage.mapper.BucketMapper;
import com.liao.cloudstorage.service.IBucketService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.minio.MinioClient;
import io.minio.errors.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.xmlpull.v1.XmlPullParserException;

import javax.annotation.Resource;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.time.LocalDate;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author liao
 * @since 2019-04-24
 */
@Service
public class BucketServiceImpl extends ServiceImpl<BucketMapper, Bucket> implements IBucketService {

    @Resource
    private BucketMapper bucketMapper;
    private MinioClient minioClient;

    @Autowired
    public BucketServiceImpl(MinioClientBean minioClientBean) {
        minioClient = minioClientBean.getMinioClient();
    }

    @Override
    public List<Bucket> getAllBucket() {
        return bucketMapper.selectList(null);
    }

    private static Logger logger = LoggerFactory.getLogger(BucketServiceImpl.class);

    @Override
    public boolean addBucket(String bucketName) {
        QueryWrapper<Bucket> queryWrapper = new QueryWrapper<Bucket>().eq("bucket_name", bucketName);
        List<Bucket> bucketList = bucketMapper.selectList(queryWrapper);
        if (bucketList.size() != 0) {
            return false;
        } else {
            Bucket bucket = new Bucket();
            bucket.setBucketName(bucketName);
            bucket.setBucketUseSize(0);
            bucket.setUserId(1);
            bucket.setCreateTime(LocalDate.now());
            boolean isExist = true;
            int insert = 0 ;
            try {
                // 判断存储桶是否存在
                if (!minioClient.bucketExists(bucketName)) {
                    minioClient.makeBucket(bucketName);
                    isExist = false;
                    insert = bucketMapper.insert(bucket);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return insert == 1 && !isExist;
        }
    }

    @Override
    public boolean deleteBucketById(Integer id) {
        Bucket bucket = bucketMapper.selectById(id);
        int i = bucketMapper.deleteById(id);
        try {
            if (minioClient.bucketExists(bucket.getBucketName())) {
                minioClient.removeBucket(bucket.getBucketName());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return i == 1;
    }


    private Bucket getBucket(String bucketName) {
        QueryWrapper<Bucket> queryWrapper = new QueryWrapper<Bucket>().eq("bucket_name", bucketName);
        return bucketMapper.selectOne(queryWrapper);
    }

    private int getFileSize(double fileSzie) {
        if ((fileSzie - (int) fileSzie) > 0.4) {
            return (int) fileSzie + 1;
        }
        return (int) fileSzie;
    }

    @Override
    public void autoAddFile(String bucketName, double fileSize) {
        logger.debug("接受信息--{},{}", bucketName, fileSize);
        Bucket bucket = getBucket(bucketName);
        bucket.setObjectNum(bucket.getObjectNum() + 1);
        bucket.setBucketUseSize(bucket.getBucketUseSize() + getFileSize(fileSize));
        logger.debug("bucket信息----> {}",bucket);
        int i = bucketMapper.updateById(bucket);
        logger.debug("i=={}", i);
    }

    @Override
    public void autoRemoveFile(String bucketName, double fileSize) {
        Bucket bucket = getBucket(bucketName);
        bucket.setObjectNum(bucket.getObjectNum() - 1);
        bucket.setBucketUseSize(bucket.getBucketUseSize() - getFileSize(fileSize));
        bucketMapper.updateById(bucket);
    }
}
